<template>
    <div>
      <!--  面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
<!--        警告区域-->
        <el-alert
          title="注意：只允许对第三季分类设置相关参数！"
          type="warning" :closable="false"  show-icon style="margin-bottom: 15px">
        </el-alert>
<!--        选择商品分类区域-->
        <el-row>
          <el-col><span>选择商品分类：</span>
            <el-cascader
              v-model="selectCateKeys"
              :options="cateList"
              :props="props"
              @change="handleChange" clearable ></el-cascader>
          </el-col>
        </el-row>
<!--        tab 页签区域-->
        <el-tabs v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" disabled v-if="this.selectCateKeys.length === 0">添加参数</el-button>
            <el-button type="primary" v-else @click="paramDialogVisible =true">添加参数</el-button>
<!--            动态参数表格  @expand-change="expandChange"-->
            <el-table :data="manyTableData" stripe style="width: 100%" border>
              <!--              展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope">
                <el-tag
                  v-for="(item ,i) in scope.row.attr_vals"
                  :key="i" @close="handleClose( scope.row,item)"
                  closable style="margin: 15px" >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
              </el-table-column>
<!--              排序列-->
              <el-table-column
                type="index" label="#">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="参数名称">
              </el-table-column>
              <el-table-column label="操作">
                // 注意template 加到这列里面
                <template slot-scope="scope" >
                <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.attr_id)" ></el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteParam(scope.row.attr_id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" disabled v-if="this.selectCateKeys.length === 0">添加属性</el-button>
            <el-button type="primary" v-else @click="paramDialogVisible =true" >添加属性</el-button>
<!--            静态属性表格-->
            <el-table :data="onlyTableData" stripe style="width: 100%" border>
              <!--              展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-tag
                    v-for="(item ,i) in scope.row.attr_vals"
                    :key="i" @close="handleClose( scope.row,item)"
                    closable style="margin: 15px" >
                    {{item}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!--              排序列-->
              <el-table-column
                type="index" label="#">
              </el-table-column>
              <el-table-column
                prop="attr_name"
                label="属性名称">
              </el-table-column>
              <el-table-column label="操作">
                // 注意template 加到这列里面
                <template slot-scope="scope" >
                <el-button type="primary" icon="el-icon-edit" circle @click="showEditDialog(scope.row.attr_id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" circle  @click="deleteParam(scope.row.attr_id)"></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
<!--      添加动态参数或添加静态属性对话框-->
      <el-dialog
        :title="this.activeName ==='many' ? '添加动态参数':'添加静态属性'"
        :visible.sync="paramDialogVisible" width="50%" @close="resetParamFiled">
        <el-form :model="addForm" :rules="addRules" ref="addRuleFormRef" label-width="100px" >
          <el-form-item :label="this.activeName ==='many' ? '动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="paramDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
      </el-dialog>
      <!--      修改动态参数或添加静态属性对话框-->
      <el-dialog
        :title="this.activeName ==='many' ? '修改动态参数':'修改静态属性'"
        :visible.sync="paramEditDialogVisible" width="50%" @close="resetEditParamFiled">
        <el-form :model="editForm" :rules="editRules" ref="editRuleFormRef" label-width="100px" >
          <el-form-item :label="this.activeName ==='many' ? '动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="paramEditDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      // 父级id列表
      selectCateKeys: [],
      //    prop配置选项 expandTrigger次级菜单的展开方式 value指定选项的值为选项对象的某个属性值
      // label指定选项标签为选项对象的某个属性值 children指定选项的子选项为选项对象的某个属性值
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      // 添加动态参数或添加静态属性对话框开关
      paramDialogVisible: false,
      // 添加动态参数或添加静态属性表单
      addForm: {
        attr_name: ''
      },
      // 添加动态参数或添加静态属性表单验证规则
      addRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      // 修改参数对话框开关
      paramEditDialogVisible: false,
      // 修改参数表单
      editForm: {
        attr_name: ''
      },
      // 修改参数的表单验证规则
      editRules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      // 当前分类id
      attrId: '',
      // tag标签 添加祥光数据
      // inputVisible: false,
      // inputValue: '',
      // tag标签数组数据
      dynamicTags: []
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取所有的分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取商品分类列表失败！') }
      // this.$message.success('获取商品分类列表成功！')
      this.cateList = res.data
    },
    //  级联组件选择数据发生变化 触发该事件
    async handleChange () {
      // console.log(this.selectCateKeys)
      // 不能选择非三级的其他节点
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        return
      }
      // 选择完节点后向后端发起获取参数请求
      const id = this.selectCateKeys[2]
      // console.log(id)
      const { data: res } = await this.$http.get('categories/' + id + '/attributes', { params: { sel: this.activeName } })
      if (res.meta.status !== 200) { return this.$message.error('获取参数失败！') }
      console.log(res)
      res.data.forEach(item => {
        // 判断item.attr_vals是否为空 为空就等于【】
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 设置自己+new tag输入框
        item.inputVisible = false
        item.inputValue = ''
      })
      // console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 监听tab 页签单机触发事件
    handleTabClick() {
      this.handleChange()
    },
    // 监听对话框关闭事件，然后重置添加表单
    resetParamFiled() {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 点击确定按钮，向数据库发起新增参数请求
    addParams() {
    // 先进行预验证
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return
        // alert(this.selectCateKeys[2])
        const id = this.selectCateKeys[2]
        // alert(this.addForm.attr_name)
        const name = this.addForm.attr_name
        const { data: res } = await this.$http.post('categories/' + id + '/attributes', {
          attr_name: name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 201) { return this.$message.error('添加失败！') }
        this.handleChange()
        this.paramDialogVisible = false
      })
    },
    // 删除参数
    async deleteParam (attrid) {
      const confirmRes = await this.$confirm('此操作将永久删除该参数 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // alert(confirmRes)
      if (confirmRes === 'confirm') {
        const id = this.selectCateKeys[2]
        // alert(id)
        const { data: res } = await this.$http.delete('categories/' + id + '/attributes/' + attrid)
        if (res.meta.status !== 200) {
          return this.$message.error('删除成功！')
        }
      }
      this.handleChange()
    },
    // 监听修改参数表单的关闭事件 在这里设置表单重置
    resetEditParamFiled() {
      this.$refs.editRuleFormRef.resetFields()
    },
    // 显示修改参数对话框事件
    async showEditDialog (attrId) {
      // 去数据库查询参数数据，回显到修改参数表单上
      // alert(this.selectCateKeys[2] + '   ' + attrId)
      const id = this.selectCateKeys[2]
      const { data: res } = await this.$http.get('categories/' + id + '/attributes/' + attrId, { attr_sel: this.activeName })
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('修改参数失败') }
      this.editForm.attr_name = res.data.attr_name
      // 定义当前分类id
      this.attrId = res.data.attr_id
      this.paramEditDialogVisible = true
    },
    // 点击确定 提交修改参数事件
    editParams() {
      this.$refs.editRuleFormRef.validate(async valid => {
        if (!valid) return
        // alert(this.selectCateKeys[2] + '   ' + this.attrId)
        const id = this.selectCateKeys[2]
        const { data: res } = await this.$http.put('categories/' + id + '/attributes/' + this.attrId, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) { this.$message.error('修改参数失败！') }
        // console.log(res)
        this.paramEditDialogVisible = false
        this.handleChange()
      })
    },
    // tag标签关闭事件 删除
    async handleClose (data, tag) {
      this.dynamicTags = data.attr_vals
      // console.log(data)
      // console.log(this.selectCateKeys[2])
      const confirmRes = await this.$confirm('此操作将永久删除该标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes === 'confirm') {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
        // console.log(dynamicTags)
        // 得到dynamicTags标签数组字符串 并向数据库更新数据
        this.dynamicTagsToStringAndUpdate(data)
        this.$message.success('删除成功！')
      }
    },
    // +tag标签点击新增标签事件
    showInput(row) {
      row.inputVisible = true
      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus()
      // })
    },
    // blur失去焦距input数据确认事件
    handleInputConfirm(data) {
      this.dynamicTags = data.attr_vals
      const inputValue = data.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
        this.dynamicTagsToStringAndUpdate(data)
        this.$message.success('添加成功')
      }
      data.inputVisible = false
      data.inputValue = ''
    },
    // 将dynamicTags标签数组变为字符串 并向数据库发起请求
    async dynamicTagsToStringAndUpdate (data) {
      // 分类 ID
      const id = this.selectCateKeys[2]
      // 属性 ID
      const attrId = data.attr_id
      // 参数的属性值（应该为字符串）
      var attrVals = ''
      for (var i = 0; i < this.dynamicTags.length; i++) {
        if (i === this.dynamicTags.length - 1) {
          attrVals = attrVals + this.dynamicTags[i]
        } else {
          attrVals = attrVals + this.dynamicTags[i] + ' '
        }
      }
      // 向数据库 编辑提交参数
      const { data: res } = await this.$http.put('categories/' + id + '/attributes/' + attrId, {
        attr_name: data.attr_name,
        attr_sel: this.activeName,
        attr_vals: attrVals
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑失败！')
      }
      console.log(res)
    }
    // TODO （这里有个小bug 已解决） 当用户对某一行展开或者关闭的时候会触发该事件
    // expandChange(row) {
    //   console.log(row)
    // }

  }
}
</script>
<style lang="less" scoped>
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
